package com.ken.apollo.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ken.apollo.commons.exception.ServiceException;
import com.ken.apollo.domain.bo.CarouselImageBo;
import com.ken.apollo.domain.entity.CarouselImage;
import com.ken.apollo.domain.query.CarouselImageQuery;
import com.ken.apollo.domain.vo.CarouselImageVo;
import com.ken.apollo.mapper.CarouselImageMapper;
import com.ken.apollo.service.CarouselImageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 轮播图表(CarouselImage)表服务实现类
 *
 * @author Ken
 * @since 2025-11-03
 */
@Slf4j
@Service
public class CarouselImageServiceImpl extends ServiceImpl<CarouselImageMapper, CarouselImage> implements CarouselImageService {

    /**
     * 保存轮播图
     *
     * @param carouselImageBo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean save(CarouselImageBo carouselImageBo) {
        log.info("【保存轮播图】请求参数：{}", carouselImageBo);

        if (ObjectUtil.isEmpty(carouselImageBo.getImagePath())) {
            throw new ServiceException("轮播图图片不能为空！");
        }

        CarouselImage carouselImage = new CarouselImage();
        BeanUtil.copyProperties(carouselImageBo, carouselImage, CopyOptions.create().ignoreNullValue().ignoreError());

        // 如果没有设置排序，默认设置为最大值+1
        if (carouselImage.getSortOrder() == null) {
            Integer maxSortOrder = this.lambdaQuery()
                    .select(CarouselImage::getSortOrder)
                    .orderByDesc(CarouselImage::getSortOrder)
                    .last("limit 1")
                    .list()
                    .stream()
                    .findFirst()
                    .map(CarouselImage::getSortOrder)
                    .orElse(0);
            carouselImage.setSortOrder(maxSortOrder + 1);
        }

        // 如果没有设置状态，默认启用
        if (carouselImage.getStatus() == null) {
            carouselImage.setStatus(true);
        }

        return super.save(carouselImage);
    }

    /**
     * 更新轮播图
     *
     * @param carouselImageBo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean update(CarouselImageBo carouselImageBo) {
        log.info("【更新轮播图】请求参数：{}", carouselImageBo);

        if (carouselImageBo.getId() == null) {
            throw new ServiceException("轮播图ID不能为空！");
        }

        CarouselImage carouselImage = new CarouselImage();
        BeanUtil.copyProperties(carouselImageBo, carouselImage, CopyOptions.create().ignoreNullValue().ignoreError());

        return super.updateById(carouselImage);
    }

    /**
     * 查询轮播图列表
     *
     * @param query
     * @return
     */
    @Override
    public List<CarouselImageVo> list(CarouselImageQuery query) {
        log.info("【查询轮播图列表】请求参数：{}", query);

        LambdaQueryWrapper<CarouselImage> wrapper = new LambdaQueryWrapper<>();
        
        if (query != null) {
            if (query.getId() != null) {
                wrapper.eq(CarouselImage::getId, query.getId());
            }
            if (query.getStatus() != null) {
                wrapper.eq(CarouselImage::getStatus, query.getStatus());
            }
        }
        
        // 按排序顺序升序排列
        wrapper.orderByAsc(CarouselImage::getSortOrder);

        List<CarouselImage> list = super.list(wrapper);

        return list.stream().map(carouselImage -> {
            CarouselImageVo vo = new CarouselImageVo();
            BeanUtil.copyProperties(carouselImage, vo);
            return vo;
        }).collect(Collectors.toList());
    }

    /**
     * 根据ID查询轮播图
     *
     * @param id
     * @return
     */
    @Override
    public CarouselImageVo getById(Long id) {
        log.info("【根据ID查询轮播图】ID：{}", id);

        CarouselImage carouselImage = super.getById(id);
        if (carouselImage == null) {
            return null;
        }

        CarouselImageVo vo = new CarouselImageVo();
        BeanUtil.copyProperties(carouselImage, vo);
        return vo;
    }

    /**
     * 更新轮播图状态
     *
     * @param id
     * @param status
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateStatus(Long id, Boolean status) {
        log.info("【更新轮播图状态】ID：{}，状态：{}", id, status);

        CarouselImage carouselImage = new CarouselImage();
        carouselImage.setId(id);
        carouselImage.setStatus(status);

        return super.updateById(carouselImage);
    }

    /**
     * 更新轮播图排序
     *
     * @param id
     * @param sortOrder
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateSortOrder(Long id, Integer sortOrder) {
        log.info("【更新轮播图排序】ID：{}，排序：{}", id, sortOrder);

        CarouselImage carouselImage = new CarouselImage();
        carouselImage.setId(id);
        carouselImage.setSortOrder(sortOrder);

        return super.updateById(carouselImage);
    }
}

